<template>
  <div>
    <el-drawer
      :title="
        drawer.type === 'edit'
          ? '编辑优惠券'
          : drawer.type === 'new'
          ? '新增优惠券'
          : '优惠券详情'
      "
      :visible.sync="drawer.show"
      size="50%"
      direction="rtl"
      custom-class="add-drawer"
      :before-close="handleClose"
    >
      <p class="title-text" style="margin-left: 14px">优惠券-基础信息</p>
      <el-form
        ref="createForm"
        v-if="createForm"
        :model="createForm"
        :rules="rules"
        label-position="right"
        label-width="100px"
        class="formSty"
      >
        <!-- 优惠券名称 -->

        <el-form-item
          :rules="[
            { required: true, message: '优惠券名称不能为空', trigger: 'blur' },
            { validator: validatecouponRemark, trigger: 'blur' },
          ]"
          prop="couponRemark"
        >
          <span slot="label" class="slot_form_label">优惠券名称</span>
          <el-input
            type="text"
            placeholder="名称不能为空"
            v-model="createForm.couponRemark"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item
        :rules="[
    { required: true, message: '优惠券名称不能为空', trigger: 'blur' },
    { validator: validatecouponRemark, trigger: 'blur' }
  ]"
        prop="couponRemark"
      >
      <span
          slot="label"
          class="slot_form_label"
        >优惠券名称</span>
        <span class="lr-text">每人可领</span>
        <el-input
          type="text"
          v-model="createForm.couponRemark"
          style="width: 40%;margin: 0 8px;"
          :disabled="drawer.type === 'read'"
        ></el-input>
        <span class="lr-text">张</span>
      </el-form-item> -->

        <!-- 优惠券ID -->
        <el-form-item prop="id">
          <span slot="label" class="slot_form_label">优惠券ID</span>
          <input
            type="text"
            v-model="createForm.id"
            placeholder="无需输入，系统自动生成"
            disabled
            class="form-control"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 优惠券类型 -->
        <el-form-item
          label="优惠券类型"
          prop="couponType"
          :rules="{
            required: true,
            message: '请选择优惠券类型',
            trigger: 'change',
          }"
        >
          <span slot="label" class="slot_form_label">优惠券类型</span>
          <el-select
            v-model="createForm.couponType"
            clearable
            placeholder="请选择"
            :disabled="drawer.type === 'read'"
          >
            <el-option label="现金券" value="1" />
            <el-option label="折扣劵" value="2" />
            <!-- <el-option label="兑换劵" value="3" /> -->
            <el-option label="洗车劵" value="4" />
            <el-option label="立减券" value="5" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item
        v-show="createForm.couponType == 5"
        label="立减类型"
        prop="reductionType"
      >
        <span slot="label" class="slot_form_label">立减类型</span>
        <el-select
          v-model="createForm.reductionType"
          clearable
          placeholder="请选择"
          :disabled="drawer.type === 'read'"
        >
          <el-option label="定额立减" value="quota" />
          <el-option label="百分比立减" value="percentage" />
        </el-select>
      </el-form-item> -->
      <el-form-item prop="isMergeUse" >
          <span slot="label" class="slot_form_label">是否合并使用</span>
          <el-radio-group v-model="createForm.isMergeUse" :disabled="drawer.type !== 'new'">
            <el-radio :label="0">不允许合并使用</el-radio>
            <el-radio :label="1">允许合并使用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="['1', '4', '5'].includes(createForm.couponType)"
          :rules="[
            { required: true, message: '面值不能为空', trigger: 'blur' },
            { validator: validateCouponAmt, trigger: 'blur' },
          ]"
          prop="couponAmt"
        >
          <span slot="label" class="slot_form_label">优惠卷面值</span>
          <span class="lr-text">{{
            createForm.couponType == 5 ? "每升立减" : "固定面值"
          }}</span>
          <el-input
            type="text"
            v-model="createForm.couponAmt"
            style="width: 40%; margin: 0 8px"
            :disabled="drawer.type === 'read'"
          ></el-input>
          <span class="lr-text">元</span>
        </el-form-item>

        <!-- <el-form-item
        v-show="createForm.couponType == 1"
        prop="couponAmt"
        :rules="[
    { required: true, message: '面值不能为空', trigger: 'blur' },
    { validator: validateCouponAmt, trigger: 'blur' }
  ]"
      >
        <span
          slot="label"
          class="slot_form_label"
        >优惠卷面值</span>
        <span class="lr-text">固定面值</span>
        <input
          type="text"
          v-model="createForm.couponAmt"
          class="form-control input-lr-text"
          :disabled="drawer.type === 'read'"
        />
        <span class="lr-text">元</span>
      </el-form-item> -->

        <el-form-item
          v-show="createForm.couponType == 2"
          :rules="[
            { required: true, message: '面值不能为空', trigger: 'blur' },
            { validator: validateCouponAmt, trigger: 'blur' },
          ]"
          prop="couponAmt"
        >
          <span slot="label" class="slot_form_label">折扣率</span>

          <el-input
            type="text"
            v-model="createForm.couponAmt"
            style="width: 40%; margin: 0 8px"
            :disabled="drawer.type === 'read'"
          ></el-input>
          <span class="lr-text">%</span>
        </el-form-item>

        <!-- <el-form-item
        v-show="createForm.couponType == 2"
        prop="couponAmt"
        :rules="[
    { required: true, message: '面值不能为空', trigger: 'blur' },
    { validator: validateCouponAmt, trigger: 'blur' }
  ]"
      >
        <span
          slot="label"
          class="slot_form_label"
        >折扣率</span>
        <input
          type="text"
          v-model="createForm.couponAmt"
          class="form-control input-lr-text"
          :disabled="drawer.type === 'read'"
        />
        <span class="lr-text">%</span>
      </el-form-item> -->

        <el-form-item
          v-if="['1', '2', '5'].includes(createForm.couponType)"
          :rules="[
            { required: true, message: '使用条件不能为空 ', trigger: 'blur' },
            { validator: validateCouponUserAmt, trigger: 'blur' },
          ]"
          prop="couponThresholdAmt"
        >
          <span slot="label" class="slot_form_label">使用条件</span>
          <span class="lr-text">消费满</span>
          <el-input
            type="text"
            v-model="createForm.couponThresholdAmt"
            style="width: 40%; margin: 0 8px"
            :disabled="drawer.type === 'read'"
          ></el-input>
          <span class="lr-text">元</span>
        </el-form-item>

        <!-- <el-form-item
        v-show="['1', '2'].includes(createForm.couponType)"
        :rules="[
    { required: true, message: '面值不能为空', trigger: 'blur' },
    { validator: validateCouponAmt, trigger: 'blur' }
  ]"
        prop="couponThresholdAmt"
      >
        <span
          slot="label"
          class="slot_form_label"
        >使用条件</span>
        <span
          class="lr-text"
          style="margin-left: 15px;"
        >消费满</span>
        <input
          type="text"
          v-model="createForm.couponThresholdAmt"
          class="form-control input-lr-text"
          :disabled="drawer.type === 'read'"
        />
        <span class="lr-text">元</span>
      </el-form-item> -->

        <el-form-item
          prop="couponNum"
          :rules="[
            { required: true, message: '生成数不能为空', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' },
          ]"
        >
          <span slot="label" class="slot_form_label">生成数</span>
          <el-input
            v-model.number="createForm.couponNum"
            type="text"
            placeholder="请输入优惠券生成的数量"
            style="width: 40%; margin-right: 8px"
            :disabled="drawer.type === 'read'"
          ></el-input>
          <span class="lr-text">张</span>
        </el-form-item>

        <!-- <el-form-item
        :rules="[{ required: true, message: '可使用数不能为空', trigger: 'blur' },]"
        prop="giveCount"
      >
        <span
          slot="label"
          class="slot_form_label"
        >月使用限制</span>
        <span class="lr-text">每人每月可使用</span>
        <el-input
          type="number"
          v-model.number="createForm.giveCount"
          style="width: 40%;margin: 0 8px;"
          :disabled="drawer.type === 'read'"
        ></el-input>
        <span class="lr-text">张</span>
      </el-form-item> -->

        <el-form-item
          :rules="[
            { required: true, message: '领取数不能为空', trigger: 'blur' },
            { validator: validateGiveNumber, trigger: 'blur' },
          ]"
          prop="giveCount"
        >
          <span slot="label" class="slot_form_label">领取限制</span>
          <span class="lr-text">每人可领</span>
          <el-input
            type="text"
            v-model.number="createForm.giveCount"
            style="width: 40%; margin: 0 8px"
            :disabled="drawer.type === 'read'"
          ></el-input>
          <span class="lr-text">张</span>
        </el-form-item>

        <!-- <el-form-item label="能否叠加" :rules="{
                required: true,
                message: '请选择能否叠加',
                trigger: 'change',
            }">
                <el-radio-group>
                    <el-radio label="1">是</el-radio>
                    <el-radio label="2">否</el-radio>
                </el-radio-group>
            </el-form-item> -->
        <!-- 其他表单项省略，按照上面的例子继续添加表单项并设置:disabled="drawer.type === 'read'"属性 -->
        <!-- ... -->

        <!-- 发放时间 -->
        <el-form-item
          prop="allDate"
          :rules="{
            required: true,
            message: '请选择发放时间',
            trigger: 'change',
          }"
        >
          <span slot="label" class="slot_form_label">发放时间</span>
          <el-date-picker
            style="width: 350px"
            v-model="createForm.allDate"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="drawer.type === 'read'"
          >
          </el-date-picker>
        </el-form-item>

        <!-- 使用有效期 -->
        <el-form-item prop="effectiveTimeType">
          <span slot="label" class="slot_form_label">使用有效期</span>
          <div>
            <div>
              <el-radio-group
                v-model="createForm.effectiveTimeType"
                :disabled="drawer.type === 'read'"
                @change="handleRadioChange(createForm.effectiveTimeType)"
              >
                <el-radio label="1">固定时间段</el-radio>
                <el-radio label="2">固定天数</el-radio>
              </el-radio-group>
            </div>
            <div style="margin-top: 10px">
              <div v-if="createForm.effectiveTimeType == 1">
                <el-date-picker
                  style="width: 350px"
                  v-model="createForm.effectiveTime"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :disabled="drawer.type === 'read'"
                >
                </el-date-picker>
              </div>
              <div v-if="createForm.effectiveTimeType == 2">
                自用户领取后
                <input
                  type="text"
                  class="form-control d-inline"
                  v-model.number="createForm.effectiveDayNum"
                  style="width: 80px"
                  :disabled="drawer.type === 'read'"
                />
                天内有效
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 优惠说明 -->
        <el-form-item
          prop="couponDetails"
          :rules="[
            { required: true, message: '优惠券名称不能为空', trigger: 'blur' },
            { validator: validateDetailRemark, trigger: 'blur' },
          ]"
        >
          <span slot="label" class="slot_form_label">优惠说明</span>
          <el-input
            type="text"
            placeholder="请输入优惠说明内容"
            v-model="createForm.couponDetails"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>

        <!-- 使用说明 -->
        <el-form-item
          prop="usageDescription"
          :rules="[
            { required: true, message: '优惠券名称不能为空', trigger: 'blur' },
            { validator: validateDetailRemark, trigger: 'blur' },
          ]"
        >
          <span slot="label" class="slot_form_label">使用说明</span>
          <el-input
            type="text"
            placeholder="请输入优惠券使用规则"
            v-model="createForm.usageDescription"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>

        <!-- 关联站点 -->
        <p class="title-text">优惠券-关联站点</p>
        <el-form-item
          label="油站名"
          prop="stationId"
          :rules="{
            required: true,
            message: '请选择油站',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="createForm.stationId"
            :clearable="true"
            filterable
            placeholder="请选择油站"
            style="width: 250px"
            :disabled="drawer.type === 'read'"
            @change="handleStationChange"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 关联商品 -->
        <p class="title-text">优惠券-关联商品</p>

        <el-form-item label="商品类型" prop="oilIdLists">
          <div>
            <div v-if="createForm.couponType != 3">
              <!-- <el-button type="primary">添加油品</el-button> -->
              <el-button
                :type="isNonOil === 'oil' ? 'primary' : ''"
                @click="oilListStationId(createForm.stationId, 'oil')"
                :disabled="drawer.type === 'read'"
              >
                添加油品
              </el-button>

              <el-button
                :type="isNonOil === 'nonOil' ? 'primary' : ''"
                @click="nonOilListStationId(createForm.stationId, 'nonOil')"
                :disabled="drawer.type === 'read'"
                v-show="
                  createForm.couponType === '1' || createForm.couponType === '2'
                "
              >
                添加非油商品
              </el-button>

              <el-row style="margin-top: 14px; width: 120%; left: -5rem">
                <el-col
                  v-show="isNonOil === 'oil'"
                  v-for="(oil, index) in createForm.oilIdLists"
                  :key="oil.oilId"
                  :span="6"
                >
                  <div class="commodity-item" :title="oil.oilName">
                    <span>{{ oil.oilName }}</span>
                    <!-- Add the "delete-button" class to the delete button icon -->
                    <span style="float: right" class="delete-button">
                      <i
                        class="el-icon-error"
                        style="color: red; cursor: pointer"
                        @click="handleRemoveOil(index)"
                      ></i>
                    </span>
                  </div>
                </el-col>

                <el-col
                  v-show="isNonOil === 'nonOil'"
                  v-for="(oil, index) in createForm.couponNotOils"
                  :key="oil.commodityId"
                  :span="6"
                >
                  <div class="commodity-item" :title="oil.commodityName">
                    <span>{{ oil.commodityName }}</span>
                    <!-- Add the "delete-button" class to the delete button icon -->
                    <span style="float: right" class="delete-button">
                      <i
                        class="el-icon-error"
                        style="color: red; cursor: pointer"
                        @click="handleRemoveNonOil(index)"
                      ></i>
                    </span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form-item>

        <!-- <div>
              <el-button type="primary" style="margin-top: 16px;">添加非油品</el-button>
              <el-row style="margin-top: 14px;">
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right;"><i class="el-icon-error" style="color: red"></i></span>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right;"><i class="el-icon-error" style="color: red"></i></span>
                  </div>
                </el-col>
              </el-row>
            </div> -->
        <!-- 其他表单项省略，按照上面的例子继续添加表单项并设置:disabled="drawer.type === 'read'"属性 -->
        <!-- <div v-if="createForm.couponType == 3">
                <p class="title-text">优惠券-核销方</p>
                <p style="text-align: center;">（自己的站点是默认必选的核销商）</p>
                <div>
                    <el-col :span="11">
                        <el-table :data="unselectedCouponList" border size="mini" :resizable="false" highlight-current-row
                            height="500" @selection-change="handleLeftChange" disabled ref="leftTable">
                            >
                            <el-table-column label="可选">
                                <el-table-column prop="phone" label="机构" type="selection"></el-table-column>
                                <el-table-column prop="stationName" label="机构"></el-table-column>
                                <el-table-column label="添加" width="60px" align="left">
                                    <template slot-scope="scope">
                                        <el-button type="text" icon="el-icon-circle-plus-outline" class="underline btn24"
                                            size="mini" @click="handleMoveLabel('right', scope.row)">添加</el-button>
                                    </template>
</el-table-column>
</el-table-column>
</el-table>
</el-col>
<el-col :span="2" style="text-align: center">
  <el-button type="primary" size="mini" @click="toggleLabel" style="
        margin-top: 200px;
        text-align: center;
        width: 30px;
        padding-right: 0;
        padding-left: 0;
      " :disabled="toggleable">切换</el-button>
</el-col>
<el-col :span="11" style="margin-bottom: 20px;">
  <el-table :data="selectedCouponList" border size="mini" highlight-current-row :resizable="false" height="500"
    @selection-change="handleRightChange" :loading="true" ref="rightTable">
    <el-table-column label="已选" :resizable="false">
      <el-table-column prop="phone" type="selection"></el-table-column>
      <el-table-column prop="stationName" label="姓名"></el-table-column>
      <el-table-column label="移除" width="60px" align="left">
        <template slot-scope="scope">
                                        <el-button type="text" icon="el-icon-remove-outline" class="underline btn24"
                                            size="mini" @click="handleMoveLabel('left', scope.row)">移除</el-button>
                                    </template>
      </el-table-column>
    </el-table-column>
  </el-table>
</el-col>
</div>
</div> -->
      </el-form>

      <!--添加油品弹框-->
      <el-dialog
        :title="'添加油品'"
        :visible.sync="oilOpen"
        width="800px"
        append-to-body
      >
        <el-table
          :data="oilList"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionOilChange"
        >
          <el-table-column type="selection"> </el-table-column>
          <el-table-column prop="oilName" label="品名" align="left">
          </el-table-column>
          <el-table-column prop="oilClass" label="类型" align="left">
          </el-table-column>
          <el-table-column prop="oilType" label="型号" align="left">
          </el-table-column>
          <el-table-column prop="unitCode" label="单位" align="left">
            <template slot-scope="scope">
              {{ scope.row.unitCode == "1" ? "升" : "" }}
              {{ scope.row.unitCode == "2" ? "千克" : "" }}
              {{ scope.row.unitCode == "3" ? "公斤" : "" }}
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer"></div>
      </el-dialog>

      <div style="text-align: right; padding: 14px">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          v-if="drawer.type === 'new'"
          type="primary"
          @click="submitForm('new')"
          :loading="btnLoading"
          >确 定</el-button
        >
        <el-button
          v-if="drawer.type === 'edit'"
          type="primary"
          @click="submitForm('edit')"
          :loading="btnLoading"
          >确 定</el-button
        >
      </div>
    </el-drawer>
    <!--添加非油品商品弹框-->
    <NonOilGoods_Add
      :dialogFormVisible.sync="dialogFormVisible"
      :stationId="stationId"
      :nonOilIdLists="nonOilIdLists"
      @getOilIdLists="getOilIdLists"
    ></NonOilGoods_Add>
  </div>
</template>
<script>
import { cloneDeep } from "lodash";
import {
  listEnterpriseStation,
  // getOilListByLogin,
  getOilListByStationId,
} from "@/api/dept";
import { createCoupon, modifyCoupon } from "@/api/coupon/creation";
import Coupon_CreateCoupon from "./Coupon_CreateCoupon.vue";
import NonOilGoods_Add from "./nonOilGoods_add.vue";

export default {
  name: "CouponCreateCoupon_Form",
  components: { Coupon_CreateCoupon, NonOilGoods_Add },
  props: {
    parm: {
      type: Object,
      default: null,
    },
  },
  data() {
    // 优惠券-关联商品-校验
    let validateOilNameList = (rule, value, callback) => {
      if (this.isNonOil === "nonOil") {
        if (this.createForm.couponNotOils.length === 0) {
          callback(new Error("请选择优惠券的使用非油商品"));
          return;
        } else {
          callback();
        }
      } else if (this.isNonOil === "oil") {
        if (this.createForm.oilIdLists.length == 0) {
          callback(new Error("请选择优惠券的使用油品"));
          return;
        } else {
          callback();
        }
      } else {
        callback(new Error("请选择优惠券关联商品"));
      }
    };
    let validateEffectiveTimeType = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请填入有效时间"));
        return;
      }
      if (value == 1) {
        if (this.createForm.effectiveTime.length == 0) {
          callback(new Error("请选择有效时间"));
          return;
        }
      }
      if (value == 2) {
        if (!this.createForm.effectiveDayNum) {
          callback(new Error("请填入有效天数"));
          return;
        }
      }
      callback();
    };
    let valiAllDate = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("请填入有效时间"));
        return;
      }
    };

    return {
      // 添加非油商品弹框
      // 添加非油商品还是油品
      isNonOil: null,
      // 传入
      nonOilIdLists: [],
      stationId: null,
      dialogFormVisible: false,

      btnLoading: false,
      loading: false,
      allDate: null,
      oilOpen: false,
      oilIdLists: [],
      oilList: [],
      stepOneData: {
        issueRemark: "",
        issueName: "",
        couponThresholdAmt: "",
        oilPartOrAll: 1,
        isimm: "",
        startDate: "",
        endDate: "",
        // getStartTime:'',
        // showIdList: [],
        // availableControl: "0",
        // appointedDaysList: [],
        // cycleDaysList: [],
        // issueType: "",
        // getThresholdAmt: "0",
        // couponIssueRelationList: [],
        // giveLimit: 9,
        // giveCount: 999999,
      },

      drawer: {
        show: this.parm ? this.parm.drawerShow : false,
        type: this.parm ? this.parm.drawerType : "read", // edit || read || new
      },
      // 表单校验

      rules: {
        oilIdLists: [
          // { required: true, message: "请选择适用油品", trigger: "change" },
          { required: true, validator: validateOilNameList, trigger: "change" },
        ],
        effectiveTimeType: [
          { required: true, message: "请输入有效期类型", trigger: "change" },
          { validator: validateEffectiveTimeType, trigger: "change" },
        ],
        allDate: [
          { required: true, message: "请输入有效期类型", trigger: "change" },
          { validator: valiAllDate, trigger: "change" },
        ],
        reductionType: [
          { required: true, message: "请选择立减类型", trigger: "change" },
        ],
      },
      datePickerRules: [
        {
          type: "array",
          required: true,
          message: "请选择日期范围",
          trigger: "change",
        },
      ],
      createForm: this.parm ? this.parm.createForm : {},

      enterpriseList: [],
      stationList: [],
    };
  },

  created() {
    // this.$refs.createForm.clearValidate();
  },
  methods: {
    handleRadioChange(value) {
      if ("2" == value) {
        this.createForm.effectiveTime = [];
      }
    },
    clearValidate() {
      this.$refs.createForm.clearValidate();
    },

    // 优惠券-关联站点 选择油站
    handleStationChange() {
      // 清空 oilIdLists
      this.createForm.oilIdLists = [];
      // 清空 couponNotOils
      this.createForm.couponNotOils = [];
    },

    validatecouponRemark(rule, value, callback) {
      if (value.length > 20) {
        callback(new Error("优惠券名称不能超过20个字符"));
      } else {
        callback();
      }
    },
    validateDetailRemark(rule, value, callback) {
      if (value.length > 100) {
        callback(new Error("优惠/使用说明不能超过100个字符"));
      } else {
        callback();
      }
    },
    validateCouponAmt(rule, value, callback) {
      // 使用正则表达式验证输入是否为保留两位小数的数字，且不超过6位数
      const regex = /^\d{1,6}(\.\d{1,2})?$/;
      const regex2 = /^(?:\d|[1-9]\d?)$/;
      if (["1", "4", "5"].includes(this.createForm.couponType)) {
        if (value === 0) {
          callback(new Error("面值不能为零"));
        }
        if (!regex.test(value)) {
          callback(new Error("请输入合法的面值，最多允许6位整数和2位小数"));
        } else {
          callback();
        }
      } else {
        if (value === 0) {
          callback(new Error("面值不能为零"));
        }
        if (!regex2.test(value)) {
          callback(new Error("请输入合法的两位整数面值"));
        } else {
          callback();
        }
      }
    },
    validateCouponZKAmt(rule, value, callback) {
      // 使用正则表达式验证输入是否为两位整数
    },
    validateCouponUserAmt(rule, value, callback) {
      // 使用正则表达式验证输入是否为保留两位小数的数字，且不超过6位数
      const regex = /^\d{1,6}(\.\d{1,2})?$/;
      if (!regex.test(value)) {
        callback(new Error("请输入合法的面值，最多允许6位整数和2位小数"));
      } else {
        callback();
      }
    },
    validateNumber(rule, value, callback) {
      // 使用正则表达式验证输入是否为数字且不超过9位数
      const regex = /^\d{1,9}$/;
      // if (value === 0) {
      //   callback(new Error("生成数不能为0"));
      // }
      if (!regex.test(value)) {
        callback(new Error("请输入合法的数字且不超过9位数"));
      } else {
        callback();
      }
    },
    validateGiveNumber(rule, value, callback) {
      // 使用正则表达式验证输入是否为数字且不超过9位数
      const regex = /^\d{1,9}$/;
      if (value === 0) {
        callback(new Error("领取限制不能为0"));
      }
      if (!regex.test(value)) {
        callback(new Error("请输入合法的数字且不超过9位数"));
      } else {
        callback();
      }
    },

    // 优惠券-关联商品 油品
    oilListStationId(stationId, add) {
      this.isNonOil = add;
      this.createForm.couponNotOils = [];

      this.loading = true;
      // 设置 oilOpen 和 stepOneData.oilPartOrAll
      this.oilOpen = true;
      this.stepOneData.oilPartOrAll = 0;
      // 调用后端接口
      getOilListByStationId(stationId)
        .then((res) => {
          // 成功获取数据后，将数据赋值给 oilList 变量
          this.oilList = res.rows;
        })
        .finally(() => (this.loading = false));
    },

    // 优惠券-关联商品 非油品商品
    nonOilListStationId(stationId, add) {
      this.isNonOil = add;
      this.createForm.oilIdLists = [];
      this.nonOilIdLists = this.createForm.couponNotOils;
      this.stationId = stationId;
      this.dialogFormVisible = true;
    },

    handleClose() {
      this.isNonOil = null;
      this.drawer.show = false;
    },

    // 选择的非油品列表数据
    getOilIdLists(multipleSelection) {
      // 已经选择的传入
      multipleSelection.forEach((element) => {
        this.createForm.couponNotOils.push(element);
      });
    },

    // 优惠券-关联商品 删除添加油品
    handleRemoveOil(index) {
      if (this.drawer.type !== "read") {
        this.createForm.oilIdLists.splice(index, 1);
      }
    },

    // 优惠券-关联商品 删除添加非油商品
    handleRemoveNonOil(index) {
      if (this.drawer.type !== "read") {
        this.createForm.couponNotOils.splice(index, 1);
      }
    },

    handleSelectionOilChange(val) {
      this.createForm.oilIdLists = val;
      this.$refs.createForm.validate((valid) => {});
      //   this.oilIdLists.splice(index, 1);
    },

    // 查询油站
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        if (res && Array.isArray(res)) {
          // 插入 "全部油企" 数据
          res.unshift({ stationId: 0, stationName: "全部油站" });
        }
        this.stationList = res;
      });
    },

    submitForm(key) {
      // 首先触发表单校验
      this.$refs.createForm.validate((valid) => {
        if (valid) {
          // 表单校验通过，执行接口请求
          if (key === "new") {
            this.btnLoading = true;

            createCoupon(this.createForm)
              .then((response) => {
                if (response && response.code === 200) {
                  this.$message.success("创建优惠券成功！");
                } else {
                  this.$message.error(response.msg);
                }

                // 接口请求成功的回调处理
                this.btnLoading = false;
                this.drawer.show = false;
                // 刷新父页面的列表数据
                if (this.$parent && this.$parent.getList) {
                  this.$parent.getList();
                }
              })
              .catch((error) => {
                this.btnLoading = false;
                // 接口请求失败的回调处理
                console.error("优惠券创建失败:", error);
                // 表单校验失败时，将 allDate 重新赋值给 createForm.allDate
              });
          } else if (key === "edit") {
            this.btnLoading = true;

            modifyCoupon(this.createForm)
              .then((response) => {
                if (response && response.code === 200) {
                  this.$message.success("修改优惠券成功！");
                } else {
                  this.$message.error(response.msg);
                }

                // 接口请求成功的回调处理
                this.btnLoading = false;
                this.drawer.show = false;
                // 刷新父页面的列表数据
                if (this.$parent && this.$parent.getList) {
                  this.$parent.getList();
                }
              })
              .catch((error) => {
                // 接口请求失败的回调处理
                this.btnLoading = false;
                console.error("优惠券创建失败:", error);
                // 表单校验失败时，将 allDate 重新赋值给 createForm.allDate
              });
          }
        } else {
          this.btnLoading = false;
          // 表单校验不通过，不执行接口请求，显示错误信息
          console.log("表单校验不通过");
        }
      });
    },

    cancel() {
      this.drawer.show = false;
    },

    // 优惠券-关联商品 回显
    echoCouponProduct() {
      this.createForm.couponNotOils = this.createForm.couponNotOils
        ? this.createForm.couponNotOils
        : [];
      this.createForm.oilIdLists = this.createForm.oilIdLists
        ? this.createForm.oilIdLists
        : [];
      this.isNonOil =
        this.createForm.couponNotOils.length === 0 ? "oil" : "nonOil";
    },
  },
  watch: {
    parm(newValue) {
      this.drawer.show = newValue.drawerShow;
      this.drawer.type = newValue.drawerType;
      this.createForm = newValue.createForm;
      this.echoCouponProduct();

      // this.$refs.createForm.clearValidate();
    },
    // 监听 effectiveTimeType 的变化

    // "createForm.effectiveTimeType": function (newVal, oldVal) {
    //   // 当 effectiveTimeType 变化时，清空 effectiveTime
    //   if (this.drawer.type === "new" || this.drawer.type === "edit") {
    //     if (newVal !== oldVal) {
    //       this.createForm.effectiveTime = [];
    //     }
    //   }
    // },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .add-drawer {
  overflow-y: auto;
}

.title-text {
  // padding: 0 16px;
  font-size: 24px;
}

.input-lr-text {
  display: inline-block;
  width: 32%;
  margin: 0 8px;
}

.formSty {
  padding: 20px;
}

.lr-text {
  display: inline-block;
  vertical-align: top;
}

.commodity-item {
  border: 1px solid #9a9a9a;
  border-radius: 20px;
  padding: 0 8px;
  margin: 0 8px 8px 0;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* Update the width to make the box wider */
  // width: 80px;
  /* Add these properties to handle long text */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
}

.delete-button {
  /* Add absolute positioning to the delete button */
  position: absolute;
  margin-right: 10px;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
}

::v-deep .el-drawer__body {
  padding: 16px;
}
</style>
